<?php
  /** Une classe représentant logs utilisateurs
   * Auteur : Sebastian Mosser
   */
   
class Log implements iPersistantData, iLookable , iHTMLViewable {

   private $_id;
   private $_userLogin;
   private $_dateTime;
   private $_webFeatureUrl;
   private $_ipAdress;
	
	public function __construct($ul,$wf,$dT = "", $id = -1) {
	   $this->_id = $id;
	   $this->_userLogin = $ul;
	   $this->_dateTime = ($dT == ""? date("Y-m-d / H:i:s / U") : $dT);
	   $this->_ipAdress = $_SERVER["REMOTE_ADDR"];
	   $this->_webFeatureUrl = $wf;
	}   

	/** Implementation de l'interface iPersistantData **/

	public static function createTable() {
		$myDb = Database::getSingleton();
      $query  = "CREATE TABLE IF NOT EXISTS `log` (\n";
		$query .= "  `id`              INTEGER      NOT NULL PRIMARY KEY auto_increment, \n"; 
		$query .= "  `user_login`      VARCHAR(30)  NOT NULL, \n ";
		$query .= "  `date_time`       VARCHAR(50)  NOT NULL, \n";
		$query .= "   `ip_adress`      VARCHAR(20)  NOT NULL, \n";
		$query .= "  `web_feature_url` VARCHAR(255) NOT NULL); ";
		$myDb->execute($query);
	}
	
	public static function dropTable() {
		$myDb = Database::getSingleton();
      $query = "DROP TABLE IF EXISTS `log`;";
		$myDb->execute($query);
	}
	
	public function create() {
		$myDb = Database::getSingleton();
		if ($this->_id != -1)
			throw new RuntimeException("Log/create()",
												"This object is still present in database !");
		// Creation dans la table persistante
		$userLogin      = Database::escape($this->_userLogin);
		$dateTime       = Database::escape($this->_dateTime);
		$webFeatureUrl  = Database::escape($this->_webFeatureUrl);
		$ipAdress       = Database::escape($this->_ipAdress);
		$query  = "INSERT INTO `log` VALUES (\n";
		$query .= "  '', '$userLogin', '$dateTime', '$ipAdress','$webFeatureUrl'); ";
		/**
		$myDb->execute($query);
		($myDb->lastKeyValue() != 0 ? $this->_id = $myDb->lastKeyValue() : $this->_id = -1);
		**/
		$result = $myDb->executeInsert($query);
		if ($result[0] != 0)
			$this->_id = $result[0];
		else
			$this->id = -1;
	}
	
	public static function read($key) {
		$myDb = Database::getSingleton();
	  $key = Database::escape($key);
		$query = "SELECT * FROM `log` WHERE `id` = $key;";
		
		$ans = Database::assoc($myDb->execute($query));
		if (! $ans)
			throw new RuntimeException("Log/read()","Unknown '$key'");
		
		$aLog = new Log($ans["user_login"], $ans["web_feature_url"], $ans["date_time"], $ans["id"]);
		$aLog->_ipAdress = $ans["ip_adress"];
		return $aLog;
	}

	public function update() {
		throw new RuntimeException("Log/update()","You NEVER have to update a log !");
	}
	
	// supression d'un element
	public function delete() {
		$myDb = Database::getSingleton();
		if ($this->_id == -1)
			throw new RuntimeException("Log/delete()",
												"This object isn't present in database !");
		$query = "DELETE FROM `log` WHERE `id` = '$this->_id';";
		$myDb->execute($query);
	}

	public function tag() {
	 		$tmp = array();
	 		$tmp[0] = "Log";
	 		$tmp[1] = $this->_id;
	 		return $tmp;
	}

	 public function soundsLike($o) {
	 		return False; // such a case can never happend for Log ... :p
	 	}
	 	
	/** Fin de l'implementation de l'interface iPersistantData **/

	/** Implementation de l'interface de recherche **/
	public static function lookFor($filter) {
		
		$login = PropRetriever::getOnIndex($filter,0);
		$date = PropRetriever::getOnIndex($filter,1);
		
		$query = "";
		
		if ($login == "" && $date = "")
			return null;
		if ($login != "") 
			$query = "SELECT * FROM `log` WHERE `user_login` = '$login' ";
		if ($date != "")
			$query .= " AND `date_time` LIKE \"$date%\"";
		
		$query .= " ORDER BY `date_time` DESC;";
		$myDb = Database::getSingleton();
		
		return $myDb->execute($query);
	}
	
	public static function showResult($resultSet,$scriptUrl = ""){ 
	
		$result  = "<div align=\"center\">\n";
    $result .= "  <table class=\"resultset\">\n";
    $result .= "    <tr><th>Identifiant</th>";
    $result .= "    <th>Nom de login</th>";
    $result .= "    <th>Date</th>";
    $result .= "    <th>Adresse IP</th>";
    $result .= "    <th>Service URL</th>";
    $result .= "  </tr>\n";
    
    $tmp = "";
    $i = 0;
    while (($row = Database::assoc($resultSet))  != False) {
    	$i++;
    	$log = self::read($row["id"]);
    	$tmp .= "<tr>" .$log->displayInline()."</tr>\n";
    }
    
    if ($i == 0) {
      $result = "<p><center><span class=\"error\">";
      $result .= "Votre recherche ne donne aucun résultats :'( ";
      $result .= "</span></center></p>";
    }
    else {
    	$howMany = "<p> Votre recherche retourne ${i} entrées </p>";
    	$result = $howMany . $result;
      $result .= $tmp."  </table>\n</div>\n";
    }  
	  return $result;
	  
	}
	
	/** Fin de l'implementation de iLookable **/

	/** Implementation de l'interface de vision HTML **/
	
	public function displayLong() {
		return "";
	}
	
	public function displayShort() {
		return "";
	}

	public function displayInline($scriptUrl = "") {
		$ans = "<td>".$this->_id ."</td>";
		$ans .= "<td>".$this->_userLogin ."</td>";
		$ans .= "<td>".$this->_dateTime ."</td>";
		$ans .= "<td>".$this->_ipAdress ."</td>";
		
		if (ereg("/FAIL/",$this->_webFeatureUrl))
      $ans .= "<td> <span class=\"error\">".$this->_webFeatureUrl ."</span></td>";
		else
			$ans .= "<td> <code>".$this->_webFeatureUrl ."</code></td>";
		
		return $ans;
	}
	
	/** Fin de l'impelmentation d'iHTMLViewable **/


  /** Accès aux logs via Bajax **/
  public static function bajax_show($params) {
   $acl = array(); $acl[] = 7; Bajax::secureInvoke($acl);
   return self::showResult(self::lookFor($params));
  }

  public static function bajax_drop($params) {
   $acl = array(); $acl[] = 7; Bajax::secureInvoke($acl);
   self::dropTable();
   self::createTable();
   $ans = "<center><span class=\"error\">";
   $ans .= "Destruction des logs effectuée avec succès !</span> </center>";
   return $ans;
  }

  /** Code helper pour manipuler les logs **/

  // Renvoi les noms des utilisateurs loggé dans la base
  public static function getLoggedUser() {
  	$query = "SELECT DISTINCT `user_login` FROM `log`; ";
  	$myDb = Database::getSingleton();
  	$ans = $myDb->execute($query);

  	$result = array();
		while (($row = Database::assoc($ans)) != False) 
			$result[] = $row["user_login"];

		return $result;

  }


}

?>